<?php
if (!defined('ROOT_PATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------
// | 项目说明：
// +----------------------------------------------------------------------
// | 本页功能：文件上传类，图片的缩略亦集中与此
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://www.itye.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 吴锋(7462679@qq.com)
// +----------------------------------------------------------------------
class UpLoad
{
	// 文件大小
	public $MaxSize 		= 5000000;
	
	// 保存目录	
	public $UpLoadDir 		= 'uploads/';
	
	// 保存方式
	public $SaveType 		= 1;
	
	// 命名方式
	public $NameType 		= 1;
	
	// 允许的文件类型
	public $AllowExt 		= array('jpg', 'gif', 'png', 'bmp', 'txt', 'rar', 'doc', 'xls');
	
	private $imgExt			= array('jpg', 'gif', 'png');
	
	private $MkSubDirEd 	= false;
	
	private $upFiles 		= array();
	
	// 是否生成缩略图
	public $CreateThumb		= false;

	public $CreateType		= 1;
	
	// 缩略图大小
	public	$ThumbWidth 	= 210;
	
	public 	$ThumbHeight 	= 1000;

	/*--------------------------------------
	 * Consstruct
	 * @param string	$UpLoadDir
	 * @param string	$AllowExt
	 * @param int		$SaveType
	 * @param int		$NameType
	 * @param int		$MaxSize
	//-------------------------------------*/
	public function __construct($MaxSize = '', $UpLoadDir = '', $AllowExt = '', $NameType = 1)
	{
		if( !empty($maxSize) && is_numeric($maxSize) )
		{
			$this->MaxSize = $MaxSize;	// 自定义了上传文件大小
		}
		if ( !empty($UpLoadDir) )
		{
			$this->UpLoadDir = $UpLoadDir;
		}
		if ( !empty($AllowExt) )
		{
			$this->AllowExt = $AllowExt;
		}
		$this->NameType 	= $NameType;
		$this->_createDir($this->UpLoadDir);	// 检测目录，如没有则生成
	}
	
	// 开始上传的操作，并保存
	public function saveUpload($FileName)
	{
		if ( isset($_FILES[$FileName]) ) {
			// 说明有上传文件
			$file = $_FILES[$FileName];
			$file['tmp_name'] = str_replace('\\\\', '\\', $file['tmp_name']);
			if(!is_uploaded_file($file['tmp_name']) || !($file['tmp_name'] != 'none' && $file['tmp_name'] && $file['name'])) {
				return $this->Error(1);
			}
			if ( $file['size'] > $this->MaxSize ){
				return $this->Error(2);
			}
			// Check Ext
			if(!empty($this->AllowExt) && !in_array($this->_getExt($file['name']), $this->AllowExt)) {
				return $this->Error(3);
			}
			//成功上传返回成功信息
			$this->upFiles = $this->saveFile($file);
			return $this->upFiles;
		} else {
			return $this->Error(1);
		}
	}
	// 保存上传文件
	private function saveFile($file)
	{
		$upFile 				= array();
		$upFile['path'] 		= $this->UpLoadDir;
		$upFile['filename'] 	= $file['name'];
		if ( $this->NameType==1 ){
			$upFile['name'] 	= date("YmdHis").$this->random(5, 1);
		}else{
			$upFile['name'] 	= $file['name'];
		}
		$upFile['extension'] 	= $this->_getExt($file['name']);
		$upFile['new_file']		= $upFile['name'].'.'.$upFile['extension'];
		$upFile['size'] 		= $file['size'];
		$upFile['isimage'] 		= 0;
		$destination 			= $upFile['path'].$upFile['new_file'];
		$destination			= str_replace( "//", "/", $destination);
		$upFile['filePath']		= $upFile['path'].$upFile['new_file'];
		$upFile['filePath']		= str_replace(ROOT_PATH, "", $upFile['filePath']);
		unset($upFile['path']);
		if(move_uploaded_file($file['tmp_name'], $destination)) {
			if ( !in_array($upFile['extension'], $this->AllowExt) ){
				@unlink($destination);
				return $this->Error(3);
			}
			if(in_array($upFile['extension'], $this->imgExt)) {
				// 是图片文件
				$upFile['isimage'] = 1;
				if ($this->CreateThumb) {
					$upFile['thumb']	= $this->thumb($destination);
				}
			}
			return $upFile;
		}
	}
	/*-----------------------------------------------
	 * 缩略图
	 * @param string	$SourceFile		原图片
	 * @param string	$SavePath		保存路径
	 * @param int		$ThumbWidth		缩略宽度
	 * @param int		$ThumbHeight	缩略高度
	 * @param int		$x				X轴坐标
	 * @param int		$y				Y轴坐标
	//---------------------------------------------*/
	public function thumb($SourceFile = ''){
		$img = @getimagesize($SourceFile);
		switch($img[2]){
			case 1:
				return;
				$im=@imagecreatefromgif($SourceFile);
			break;
			case 2:
				$im=@imagecreatefromjpeg($SourceFile);
			break;
			case 3:
				$im=@imagecreatefrompng($SourceFile);
			break;
		}
		list($ImgWidth, $ImgHeight) = $img;
		if ( empty($SavePath) ){
			$SavePath = pathinfo($SourceFile, PATHINFO_DIRNAME).'/';
		}
		$FileExt	= $this->_getExt($SourceFile);
		// 缩略图名称
		$ThumbName = basename($SourceFile,".".$FileExt).'_thumb.jpg';
		if ($this->CreateType==1){
			// 按比例缩放
			$XRation = $this->ThumbWidth / $ImgWidth;
			$YRation = $this->ThumbHeight / $ImgHeight;
			if(($XRation * $ImgHeight) < $this->ThumbHeight) {
				$thumb['height'] = ceil($XRation * $ImgHeight);
				$thumb['width'] = $this->ThumbWidth;
			} else {
				$thumb['width'] = ceil($YRation * $ImgWidth);
				$thumb['height'] = $this->ThumbHeight;
			}
			$ThumbPhoto = imagecreatetruecolor($thumb['width'], $thumb['height']);
			imagecopyresampled($ThumbPhoto, $im ,0, 0, 0, 0, $thumb['width'], $thumb['height'], $ImgWidth, $ImgHeight);
			clearstatcache();
			if ( $this->SaveType == 1 ){
				imagejpeg($ThumbPhoto, $SavePath.$ThumbName,90);
				$thumbFile	= $SavePath.$ThumbName;
			}else{
				imagejpeg($ThumbPhoto, $SourceFile,90);
				$thumbFile	= $SourceFile;
			}
			$thumb['file']		= str_replace(ROOT_PATH, "", $thumbFile);
			return $thumb;
		}elseif ($this->CreateType==2){
			// 按指定大小缩放
			$XRation = $this->ThumbWidth / $ImgWidth; //新的宽度与原图的比例
			$YRation = $this->ThumbHeight / $ImgHeight; // 缩略的高度与原图的比较
			if(($XRation * $ImgHeight) < $this->ThumbHeight) {
				// 说明比高的比例小于宽度,这时候高度不变，
				$thumb['height'] = $this->ThumbHeight;
				$thumb['width'] = ceil($YRation * $ImgWidth);
				$thumbtype = 'height';
			} else {
				$thumb['width'] = $this->ThumbWidth;
				$thumb['height'] = ceil($XRation * $ImgHeight);
				$thumbtype = 'width';
			}
			//坐标得到后，先生成缩略图，然后再由生成的缩略图上来计算坐标，最终生成符合要求的图片。
			$ThumbPhoto = imagecreatetruecolor($thumb['width'], $thumb['height']);
			imagecopyresampled($ThumbPhoto, $im, 0, 0, 0, 0, $thumb['width'], $thumb['height'], $ImgWidth, $ImgHeight);
			clearstatcache();
			if ($this->SaveType == 1) {
				imagejpeg($ThumbPhoto, $SavePath.$ThumbName, 90);
				$temp_name	= $SavePath.$ThumbName;
			} else {
				imagejpeg($ThumbPhoto, $SourceFile,90);
				$temp_name	= $SourceFile;
			}
			// 生成了缩略图片
			// 由生成的缩略图再次缩略
			$tmp_img = imagecreatefromjpeg($temp_name);
			$o_width = imagesx($tmp_img);	//
			$o_height = imagesy($tmp_img);	//
			if ($thumbtype=='height'){
				$x = ($o_width-$this->ThumbWidth)/2;
				$y = 0;
			}else{
				$x = 0;
				$y = ($o_height-$this->ThumbHeight)/2;
			}
			$thumbPhotox = imagecreatetruecolor($this->ThumbWidth, $this->ThumbHeight);
			imagecopyresampled($thumbPhotox, $tmp_img ,0, 0, $x, $y, $this->ThumbWidth, $this->ThumbHeight, $this->ThumbWidth, $this->ThumbHeight);
			clearstatcache();
			if ( $this->SaveType == 1 ){
				imagejpeg($thumbPhotox, $SavePath.$ThumbName,90);
				$thumbFile		= $SavePath.$ThumbName;
			}else{
				imagejpeg($thumbPhotox, $SourceFile,90);
				$thumbFile		= $SourceFile;
			}
			$thumb['width']  	= $this->ThumbWidth;
			$thumb['height'] 	= $this->ThumbHeight;
			$thumb['file']   	= str_replace(ROOT_PATH, "", $thumbFile);
			return $thumb;
		}
	}
	/*--------------------------------------
	 * 检测目录，当目录不存在时自动生成
	 * 目录格式：自定义目录/年/月
	 * @param string	$fileName
	 -------------------------------------*/
	private function _createDir($dir)
	{
		if ( $this->MkSubDirEd ){
			return ;
		}
		
		$this->MkSubDirEd = true;
		
		if ( empty($dir) ){
			$this->UpLoadDir = ROOT_PATH.'/';
		}else{
			$this->UpLoadDir = ROOT_PATH.'/'.$dir.'/';
		}
		$this->UpLoadDir	= str_replace("//", "/", $this->UpLoadDir);
		if ( !is_dir($this->UpLoadDir) ){
			$this->_createDirDo($this->UpLoadDir);
		}
		if ( $this->SaveType == 1 ){
			$this->UpLoadDir .= date('Y'). '/';
			$this->_createDirDo($this->UpLoadDir);
			$this->UpLoadDir .= date('m'). '/';
		}else if($this->SaveType == 2) {
			$this->UpLoadDir .= date('Ymd').'/';
		}else {
		
		}
		$this->_createDirDo($this->UpLoadDir);
	}

	/*--------------------------------------
	 * 根据目录检测，不存在则生成
	 * @param
	 -------------------------------------*/
	private function _createDirDo($dir)
	 {
	 	if ( !is_dir($dir) ) {
	 		mkdir($dir, 0777);
			touch($dir.'index.htm');
	 	}
	 }

	/*--------------------------------------
	 * 取得当前文件扩展名
	 * @param string	$fileName
	 -------------------------------------*/
	private function _getExt($FileName) {
		return  strtolower(pathinfo($FileName, PATHINFO_EXTENSION));
	}

	/*--------------------------------------
	 * 自定错误信息
	 -------------------------------------*/
	private function Error( $err = 0 ) {
		switch ( $err ) {
			case 1:
				$err_txt	= '请上传文件';
			break;
			case 2:
				$err_txt	= '上传文件超过了设定的大小';
			break;
			case 3:
				$err_txt	= '不允许的上传文件';
			break;
		}
		$result['status']	= 0;
		$result['err_txt']	= $err_txt;
		return $result;
	}
	// 取得随机数
	private function random($length, $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric)
		{
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		}
		else
		{
			$hash = '';
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++)
			{
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}

}
?>